import { defineStore } from 'pinia'
import { login, logout, getProfile } from '@/api/modules/auth'
import { 
  getToken, setToken, 
  setUserInfo, getUserInfo as getStoredUserInfo,
  setRefreshToken, getRefreshToken, clearUserData
} from '@/utils/auth'
import router from '@/router'

export const useUserStore = defineStore('user', {
  state: () => ({
    token: getToken(),
    refreshToken: getRefreshToken(),
    userInfo: getStoredUserInfo(),
    roles: [],
    permissions: []
  }),

  getters: {
    username: (state) => state.userInfo?.username || '',
    fullName: (state) => state.userInfo?.fullName || '',
    avatar: (state) => {
      // 如果没有头像，返回默认头像
      if (!state.userInfo?.avatar) {
        return 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif';
      }
      
      // 获取头像URL
      const avatarUrl = state.userInfo.avatar;
      
      // 检查是否已经是完整URL
      if (avatarUrl.startsWith('http://') || avatarUrl.startsWith('https://')) {
        return avatarUrl;
      }
      
      // 现在使用相对路径，让前端自动处理代理
      
      // 如果以/media/开头
      if (avatarUrl.startsWith('/media/')) {
        return avatarUrl;
      }
      
      // 如果只有文件名，则添加/media/avatars/前缀
      if (!avatarUrl.includes('/')) {
        return `/media/avatars/${avatarUrl}`;
      }
      
      // 其他情况，添加/media/前缀
      return avatarUrl.startsWith('/') ? avatarUrl : `/media/${avatarUrl}`;
    },
    role: (state) => state.userInfo?.role || '',
    hasRoles: (state) => state.roles && state.roles.length > 0
  },

  actions: {
    // 用户登录
    async login(userInfo) {
      const { username, password } = userInfo
      try {
        const response = await login({ username: username.trim(), password: password })
        
        if (response.success && response.data) {
          const { data } = response
          
          // 处理头像URL，确保是完整路径
          if (data.user && data.user.avatar) {
            data.user.avatar = this.ensureFullAvatarUrl(data.user.avatar)
          }
          
          // 从响应中提取token和用户信息
          this.token = data.access_token
          this.refreshToken = data.refresh_token
          this.userInfo = data.user
          this.roles = [data.user.role] // 角色是单一字符串，转为数组
          this.permissions = data.permissions?.permissions || []
          
          // 存储token和用户信息
          setToken(data.access_token)
          setRefreshToken(data.refresh_token)
          setUserInfo(data.user)
          
          return data
        } else {
          throw new Error(response.message || '登录失败')
        }
      } catch (error) {
        return Promise.reject(error)
      }
    },

    // 获取用户信息
    async getUserInfo() {
      try {
        if (this.token) {
          const response = await getProfile()
          
          if (response.success && response.data) {
            const { data } = response
            
            // 处理头像URL，确保是完整路径
            if (data.avatar) {
              data.avatar = this.ensureFullAvatarUrl(data.avatar)
            }
            
            this.userInfo = data
            this.roles = [data.role] // 角色是单一字符串，转为数组
            this.permissions = data.permissions || []
            setUserInfo(data)
            
            return {
              user: data,
              roles: [data.role],
              permissions: data.permissions || []
            }
          } else {
            throw new Error(response.message || '获取用户信息失败，请重新登录')
          }
        } else {
          throw new Error('无访问令牌，请重新登录')
        }
      } catch (error) {
        return Promise.reject(error)
      }
    },

    // 用户登出
    async logout() {
      try {
        await logout()
        this.resetState()
        router.push('/login')
      } catch (error) {
        console.error('登出失败:', error)
        // 即使API失败也要清理本地数据
        this.resetState()
      }
    },

    // 重置令牌
    resetToken() {
      this.resetState()
    },

    // 重置状态
    resetState() {
      this.token = ''
      this.refreshToken = ''
      this.userInfo = null
      this.roles = []
      this.permissions = []
      clearUserData() // 使用统一的清除函数
    },

    // 确保头像URL是完整路径
    ensureFullAvatarUrl(url) {
      if (!url) return null;
      
      // 如果已经是绝对URL（包含http://或https://），则直接返回
      if (url.startsWith('http://') || url.startsWith('https://')) {
        return url;
      }
      
      // 使用相对路径，让前端自动处理代理
      
      // 如果以/media/开头
      if (url.startsWith('/media/')) {
        return url;
      }
      
      // 如果只有文件名，则添加/media/avatars/前缀
      if (!url.includes('/')) {
        return `/media/avatars/${url}`;
      }
      
      // 其他情况，添加/media/前缀
      return url.startsWith('/') ? url : `/media/${url}`;
    },

    // 获取当前token
    getToken() {
      return getToken()
    }
  }
})